from django.contrib import admin, messages
from django.http import HttpResponseRedirect
from django.urls import path
from django.utils.html import format_html
from django.db.models import Q

from apps.schedules.models import TimeSlot
from .models import Order, OrderItem, OrderStatusLog

# 定义 OrderItem 内联显示类
class OrderItemInline(admin.TabularInline):
    """用于在订单管理页面内联显示订单商品信息"""
    model = OrderItem
    extra = 0
    readonly_fields = ['dish_id', 'name', 'quantity', 'price']
    can_delete = False

# 定义 OrderStatusLog 内联显示类
class OrderStatusLogInline(admin.TabularInline):
    """用于在订单管理页面内联显示订单状态日志信息"""
    model = OrderStatusLog
    extra = 0
    readonly_fields = ['from_status', 'to_status', 'changed_by', 'created_at', 'note']
    can_delete = False

# 注册 Order 模型到 Django 管理界面
@admin.register(Order)
class OrderAdmin(admin.ModelAdmin):
    """管理订单模型的管理类"""
    # 定义列表显示的字段 - 新增id作为第一列
    list_display = [
        'id',  # 订单ID，显示在第一列
        'order_number', 
        'customer_info', 
        'chef_info', 
        'status', 
        'total_amount', 
        'created_at',
        'status_actions'  # 添加状态操作按钮列
    ]
    # 定义列表过滤的字段
    list_filter = [
        'status', 
        'payment_method', 
        'created_at'
    ]
    # 定义搜索字段
    search_fields = [
        'id',  # 允许搜索ID
        'order_number', 
        'customer__username', 
        'chef__user__username'
    ]
    # 定义只读字段
    readonly_fields = [
        'id',  # 详情页也显示ID
        'order_number', 
        'created_at', 
        'updated_at'
    ]
    # 定义内联显示的类
    inlines = [
        OrderItemInline, 
        OrderStatusLogInline
    ]
    # 定义字段集，用于分组显示字段
    fieldsets = (
        ('基本信息', {
            'fields': ('id', 'order_number', 'customer', 'chef', 'address')  # 字段集添加ID
        }),
        ('订单状态', {
            'fields': ('status', 'payment_method')
        }),
        ('金额信息', {
            'fields': ('subtotal', 'service_fee', 'total_amount')
        }),
        ('时间信息', {
            'fields': ('booked_time', 'pay_time', 'complete_time', 'created_at', 'updated_at')
        }),
    )

    def customer_info(self, obj):
        """显示顾客的详细信息，包括邮箱和全名"""
        return f"{obj.customer.email} ({obj.customer.get_full_name()})"
    customer_info.short_description = "顾客"
    customer_info.admin_order_field = 'customer__email'

    def chef_info(self, obj):
        """显示厨师的邮箱信息"""
        return f"{obj.chef.user.email}"
    chef_info.short_description = "厨师"
    chef_info.admin_order_field = 'chef__user__email'

    def status_actions(self, obj):
        """生成状态修改按钮，根据当前状态显示合理的下一步操作"""
        # 状态转换规则：根据业务流程定义每个状态可转换的目标状态
        status_transitions = {
            'pending': ['paid', 'cancelled'],
            'paid': ['confirmed', 'cancelled', 'refunded'],
            'confirmed': ['preparing', 'cancelled'],
            'preparing': ['cooking', 'cancelled'],
            'cooking': ['ready', 'cancelled'],
            'ready': ['delivering', 'cancelled'],
            'delivering': ['completed', 'cancelled'],
            'completed': ['refunded'],
            'cancelled': [],
            'refunded': []
        }
        
        # 状态显示名称映射，使按钮文本更友好
        status_display_names = {
            'paid': '已支付',
            'confirmed': '已确认',
            'preparing': '服务中',
            'cooking': '烹饪中',
            'ready': '已就绪',
            'delivering': '配送中',
            'completed': '已完成',
            'cancelled': '已取消',
            'refunded': '已退款'
        }

        actions = []
        current_status = obj.status
        # 获取当前状态允许的目标状态列表
        for next_status in status_transitions.get(current_status, []):
            # 生成状态修改URL
            url = f"{obj.id}/change_status/{next_status}/"
            # 使用友好的显示名称
            display_name = status_display_names.get(next_status, next_status)
            actions.append(
                f'<a class="button" href="{url}">改为{display_name}</a>'
            )
        return format_html(' '.join(actions))
    status_actions.short_description = "状态操作"

    # 添加清理订单按钮
    def changelist_view(self, request, extra_context=None):
        extra_context = extra_context or {}
        # 可以在这里添加清理按钮的权限控制，例如只允许超级管理员使用
        extra_context['show_clean_button'] = request.user.is_superuser
        return super().changelist_view(request, extra_context=extra_context)

    def get_urls(self):
        """添加自定义URL用于处理状态变更和订单清理"""
        urls = super().get_urls()
        custom_urls = [
            path(
                '<int:order_id>/change_status/<str:new_status>/',
                self.admin_site.admin_view(self.change_order_status),
                name='change-order-status',
            ),
            path(
                'clean_orders/',  # 清理订单的URL
                self.admin_site.admin_view(self.clean_orders),
                name='clean-orders',
            ),
        ]
        return custom_urls + urls

    def clean_orders(self, request):
        if not request.user.is_superuser:
            self.message_user(request, "没有权限执行此操作", level=messages.ERROR)
            return HttpResponseRedirect(request.META.get('HTTP_REFERER', '/admin/orders/order/'))

        try:
            # 与cleanup_useless_orders.py保持一致的清理条件
            from django.utils import timezone
            pending_days = 30  # 可与命令行默认值保持一致
            pending_cutoff = timezone.now() - timezone.timedelta(days=pending_days)

            # 1. 无对应厨师订单
            no_chef_order = Order.objects.filter(chef_order__isnull=True)
            
            # 2. 长期未支付的订单（叠加无厨师订单条件）
            old_pending = Order.objects.filter(
                status='pending',
                created_at__lt=pending_cutoff,
                chef_order__isnull=True
            )
            
            # 3. 无订单项的空订单
            empty_orders = Order.objects.filter(items__isnull=True)

            # 合并去重
            to_clean = (no_chef_order | old_pending | empty_orders).distinct()
            count = to_clean.count()
            to_clean.delete()

            # 恢复关联的档期（与命令行逻辑一致）
            affected_time_slots = TimeSlot.objects.filter(
                order_id__isnull=True
            ).exclude(status='available')
            updated_slots = affected_time_slots.update(status='available')

            self.message_user(
                request, 
                f"成功清理 {count} 条无效订单，恢复 {updated_slots} 个可用档期", 
                level=messages.SUCCESS
            )
        except Exception as e:
            self.message_user(request, f"清理失败: {str(e)}", level=messages.ERROR)
        
        return HttpResponseRedirect(request.META.get('HTTP_REFERER', '/admin/orders/order/'))

    def change_order_status(self, request, order_id, new_status):
        try:
            order = Order.objects.get(id=order_id)
            old_status = order.status
            
            # 定义管理员可用的状态转换规则（与status_actions保持一致）
            valid_transitions = {
                'pending': ['paid', 'cancelled'],
                'paid': ['confirmed', 'cancelled', 'refunded'],
                'confirmed': ['preparing', 'cancelled'],
                'preparing': ['cooking', 'cancelled'],
                'cooking': ['ready', 'cancelled'],
                'ready': ['delivering', 'cancelled'],
                'delivering': ['completed', 'cancelled'],
                'completed': ['refunded'],
                'cancelled': [],
                'refunded': []
            }
            
            # 验证状态转换合法性
            if new_status not in valid_transitions.get(old_status, []):
                self.message_user(
                    request, f"不能从 {old_status} 转换到 {new_status}！", level=messages.ERROR
                )
                return HttpResponseRedirect(request.META.get('HTTP_REFERER', f'/admin/orders/order/{order_id}/'))

            # 调用order.change_status()方法，触发同步创建逻辑
            success = order.change_status(
                to_status=new_status,
                changed_by=request.user,
                note=f"管理员通过后台修改状态（{old_status}→{new_status}）",
                request=request
            )

            if success:
                self.message_user(
                    request, f"订单状态已从 {old_status} 成功修改为 {new_status}", level=messages.SUCCESS
                )
            else:
                self.message_user(
                    request, f"状态修改失败（可能状态未变更）", level=messages.WARNING
                )

        except Order.DoesNotExist:
            self.message_user(request, "订单不存在！", level=messages.ERROR)
        except Exception as e:
            self.message_user(
                request, f"操作失败: {str(e)}（可能是厨师订单创建失败）", level=messages.ERROR
            )
            # 打印详细错误日志，便于排查
            import logging
            logger = logging.getLogger(__name__)
            logger.error(f"后台修改订单状态失败: {str(e)}", exc_info=True)

        return HttpResponseRedirect(request.META.get('HTTP_REFERER', '/admin/orders/order/'))

    # 自定义模板以显示清理按钮
    change_list_template = 'admin/orders/order_change_list.html'

@admin.register(OrderStatusLog)
class OrderStatusLogAdmin(admin.ModelAdmin):
    list_display = [
        'order', 
        'from_status', 
        'to_status', 
        'changed_by', 
        'created_at'
    ]
    list_filter = [
        'to_status', 
        'created_at'
    ]
    search_fields = [
        'order__order_number',
        'order__id'  # 允许通过订单ID搜索日志
    ]
    readonly_fields = [
        'order', 
        'from_status', 
        'to_status', 
        'changed_by', 
        'created_at', 
        'ip_address'
    ]
    list_display_links = ['order']
    list_per_page = 20
    ordering = ['-created_at']